<template>
  <div class="hex-container">
   <div class="iconfont zuojiantou icon" @click="toRgb"/>
    <div class="input-box">
      <input type="text" class="hex-input" v-model="hex" @keydown.enter="toRgb" maxlength="7"/>
    </div>
    <div class="title" @click.self="cpValue(copyValue)">Hex</div>
  </div>
</template>

<script lang="ts">
import { useStore } from "vuex";
import {computed, ref, watch} from 'vue';
import {hexChange} from "@/utils/tool";
// @ts-ignore
import {hexToRGB, rgbToHex} from '@/utils/convert.js'
import {message} from "ant-design-vue";
// @ts-ignore
import store from '@/store/index.js';

export default {
  // input 输入长度 7
  setup() {
    const hex = ref('')
    const conv = computed(() => store.state.convent)
    const copyValue = ref('HEX:#FFFFFF')
    const store = useStore()
    function toRgb() {
      // 转换后的rgb
      const rgbValue = hexToRGB(hexChange(hex.value))
      copyValue.value = hex.value
      if(rgbValue !== undefined) {
        store.commit('setConvent',{
          rgb: rgbValue,
          hex: hex.value,
          tag: 'FHEX'
        })
      }
    }
  
    // 监听来自rgb的值
    watch(conv,(newValue:any) => {
      if(newValue.tag === 'FRGB') {
        const conventHex = JSON.parse(JSON.stringify(newValue.hex))
        hex.value = '#' + conventHex;
        // 复制当前的hex值
        copyValue.value = '#' + conventHex;
      }
    },{
      immediate: false,
      deep: true
    })
  
    function cpValue(value:any) {
      let oInput = document.createElement("input"); //创建一个input标签
      oInput.setAttribute("value",value);   // 设置改input的value值
      document.body.appendChild(oInput); // 将input添加到body
      oInput.select(); // 获取input的文本内容
      document.execCommand("copy"); // 执行copy指令
      document.body.removeChild(oInput); // 删除input标签
      message.success(`复制成功，${value}`,2)
    }
    
    return {
      hex,toRgb,copyValue,cpValue
    }
  }
}
</script>

<style scoped lang="scss">
.title {
  margin-right: 6px;
  font-weight: bold;
}

.icon {
  font-size: 20px;
  background-color: aliceblue;
}

.hex-container {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
  align-content: center;
  flex-wrap: nowrap;
  flex-direction: row;
}

.input-box {
  width: 58%;
}

.hex-input {
  width: 100%;
  margin: 0 3px;
  border-radius: 6px;
  border: 1px solid #ced4da;
}

.hex-input,input::-webkit-outer-spin-button,
.hex-input,input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

.hex-input,input[type='number']{
  -moz-appearance: textfield;
}




</style>
